
from rest_framework import permissions, status
from rest_framework_jwt.authentication import jwt_decode_handler
from users.models import UserProfileModel


class IsOwnOrReadOnlyTo(permissions.BasePermission):
    """
        重写 has_object_permission 判断当前数据是否为创建者 (集和 JWT 的写法)
    """
    def has_object_permission(self, request, view, obj):
        token = request.META.get('HTTP_AUTHORIZATION')[5:]
        token_user = jwt_decode_handler(token)
        if token_user:
            return obj.user.id == token_user.get('user_id')
        return False


def token(request):
    """
        解析 Json Web Token
    """
    token = request.META.get('HTTP_AUTHORIZATION')[5:]
    token_user = jwt_decode_handler(token)
    user_id = token_user.get('user_id')
    # 暂未对超级管理员进行过滤
    user_info = UserProfileModel.objects.get(pk=user_id, is_staff=True, is_active=True)
    return user_info
